function E = get_q_error(R, C, qtable)
% calculate E in MME, e.g., error of change LSB
% Input:
% R -> C''- C'
% C -> C''
% qtable -> table for QF
%
% Output:
% E -> Additional Distortion caused by changing any single bit
%

[P, Q] = size(C);
E = ones(P, Q);
RmC = (R.*C) <= 0;
aC = abs(C) ~= 1;

E(RmC) = 1 - 2*abs(R(RmC));
E(aC) = 1 - 2*abs(R(aC));
% P, Q are always 8x
for i = 1:8:P
    for j = 1:8:Q
        E(i:i+7,j:j+7) = E(i:i+7,j:j+7) .* qtable;
    end
end

% for i = 1:P
%     qi = mod(i, 8);
%     if (qi == 0)
%         qi = 8;
%     end
%     for j = 1:Q
%         qj = mod(j, 8);
%         if (qj == 0)
%             qj = 8;
%         end
%         if (RmC(i,j) || aC(i,j))
%             E(i,j) = (1 - 2*abs(R(i,j))) * qtable(qi, qj);
%         end
%     end
% end
assert(min(E(:)) >= 0);
end
